package cn.mugutu.finance.service.system.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.mugutu.finance.domain.system.DictionaryType;
import cn.mugutu.finance.service.system.DictionaryTypeService;
import cn.mugutu.finance.utils.StringUtil;
import cn.mugutu.finance.dto.BaseResult;

@Service
public class DictionaryTypeServiceImpl extends BaseServiceImpl<DictionaryType>
        implements DictionaryTypeService {

    @Override
    public BaseResult saveOrUpdateDictionaryType(DictionaryType dictionaryType) {

        if (!StringUtil.stringsIsNotBlack(dictionaryType.getName(), dictionaryType.getSn())) {
            return new BaseResult(false, "请完善信息");
        }

        try {
            if (dictionaryType.getId() != null) {
                DictionaryType oldType = get(dictionaryType.getId());
                oldType.setName(dictionaryType.getName());
                oldType.setSn(dictionaryType.getSn());
                update(oldType);
                return new BaseResult(true, "修改成功");
            } else {
                if (dictionarySnIsExist(dictionaryType.getSn())) {
                    return new BaseResult(false, "操作失败,字典类型编码已经存在.");
                }
                save(dictionaryType);
                return new BaseResult(true, "保存成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResult(false, "操作失败,请检查字典类型编码是否已经存在,类型编码不可重复.");
        }
    }

    /**
     * 判断数据字典类型编号是否存在
     * @param sn
     * @return
     */
    private boolean dictionarySnIsExist(String sn) {
        List list = findByHql("FROM DictionaryType o WHERE o.sn = ? ", sn);
        if (list != null && list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public DictionaryType findBySn(String sn) {
        return (DictionaryType) getUniqueResult(" from DictionaryType o where o.sn = ? ", sn);
    }
}
